How to override [Authorize] attribute in the MVC Web API?
Posted
by
NullReference
on Stack Overflow
See other posts from Stack Overflow
or by NullReference
Published on 2012-09-06T15:36:10Z
Indexed on
2012/09/06
15:37 UTC
Read the original article
Hit count: 194
asp.net-mvc-4
|asp.net-web-api
I have a MVC Web Api Controller that uses the [Authorize] attribute at the class level. This makes all of the api methods require authorization but I'd like to create an attribute called [ApiPublic] that overrides the [Authorize] attribute. There is a similar technique described here for normal MVC controllers.
I tried creating an AuthorizeAttribute based of the System.Web.Http.AuthorizeAttribute but none of the overridden events are called if I put it on a api method that has the [Authorize] at the class level. Anyone have an idea how to override the authorize for the web api?
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ApiPublicAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.HandleUnauthorizedRequest(actionContext);
}
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
}
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
return true;
}
}
© Stack Overflow or respective owner